<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="期号" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入期号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态 " prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in stateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型 " prop="atype">
        <el-select v-model="queryParams.atype" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in getTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['channel:phase:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="phaseList" >
      <el-table-column label="期号" align="center" prop="name" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="上线检测" align="center" prop="sx" />
      <el-table-column label="六年免检" align="center" prop="mj" />
      <el-table-column label="代驾专用" align="center" prop="dj" />
      <el-table-column label="有效期(月)" align="center" prop="effectPeriod" />
      <el-table-column label="已领取" align="center" prop="total" />
      <el-table-column label="已使用" align="center" prop="used" />
      <el-table-column label="状态" align="center" prop="state" :formatter="stateFormat" />
      <el-table-column label="创建时间" align="center" prop="gmtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['channel:phase:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            class="btn"
            @click="handleShare"
            data-clipboard-action="copy"
            :data-clipboard-text="wrapUrl(scope.row)"
          >链接</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改推广渠道期号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" :append-to-body="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="期号" prop="name">
          <el-input v-model="form.name" placeholder="请输入期号" maxlength="14"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择状态">
                <el-option
                  v-for="dict in stateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型">
              <el-select v-model="form.atype" placeholder="请选择类型">
                <el-option
                  v-for="dict in getTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入优惠券金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拆分" prop="amount" v-if="form.atype == 1">
              <el-input-number  size="small" v-model="form.sx"  :min="0" :max="100" label="上线金额"></el-input-number> (上线检测)
              <el-input-number  size="small"  v-model="form.mj"  :min="0" :max="100" label="免检金额"></el-input-number> (六年免检)
            </el-form-item>

            <el-form-item label="拆分" prop="amount" v-if="form.atype == 2">
              <el-input-number  size="small" v-model="form.sx"  :min="0" :max="100" label="上线金额"></el-input-number> (上线检测)
              <el-input-number  size="small"  v-model="form.dj"  :min="0" :max="100" label="免检金额"></el-input-number> (仅限代驾)
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="有效期" prop="effectPeriod">
          <el-input-number v-model="form.effectPeriod"  :min="1" :max="100" label="请输入有效期"></el-input-number> （月）
        </el-form-item>
        <el-form-item label="使用说明" prop="intro">
          <el-input v-model="form.intro" type="textarea" autosize placeholder="请输入内容,多条请使用 竖线分割 |" />
        </el-form-item>
        <div>
          <p style="color: red">※ 注意：为简化维护操作特做一下操作说明</p>
          <p style="color: red"> 1、金额、有效期、使用说明等信息如果不填写，默认使用渠道已经维护好的信息</p>
          <p style="color: red"> 2、金额、有效期、使用说明等信息如果填写，则使用填写的</p>
          <p style="color: red"> 3、信息维护后确保无误再发布，发布后尽量不要修改信息</p>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPhase, getPhase, delPhase, addPhase, updatePhase } from "@/api/promt/phase";
import Clipboard from 'clipboard'
import defaultSettings from '@/settings'
export default {
  name: "Phase",
  props: {
    channelId: {
      type: Number
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 推广渠道期号表格数据
      phaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态  1 启用  2 禁用字典
      stateOptions: [],
      getTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelId: this.channelId,
        name: undefined,
        intro: undefined,
        state: undefined,
        atype: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      promtPre:defaultSettings.promtChannelUrl,
      promtApiPre:defaultSettings.promtChannelApiUrl,
    };
  },
  created() {
    this.getList();
    this.getDicts("promt_channel_state").then(response => {
      this.stateOptions = response.data;
    });
    this.getDicts("coupon_get_type").then(response => {
      this.getTypeOptions = response.data;
    });
  },
  methods: {
    wrapUrl(row){
      let urlPre;
      if (row.atype == 1){
        return  this.promtPre+ row.id;
      }else{
        return  this.promtApiPre  +  row.id + '/collect';
      }
    },
    handleShare() {
      let clipboard = new Clipboard('.btn')
      clipboard.on('success', e => {
        this.msgSuccess("复制成功");
        clipboard.destroy() // 使用destroy可以清楚缓存
      })
      clipboard.on('error', e => {
        this.msgError("复制失败");
        clipboard.destroy()
      })

    },
    /** 查询推广渠道期号列表 */
    getList() {
      this.loading = true;
      listPhase(this.queryParams).then(response => {
        this.phaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态  1 启用  2 禁用字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        channelId: this.channelId,
        name: undefined,
        atype: 1,
        amount: undefined,
        sx: undefined,
        mj: undefined,
        dj: undefined,
        background: undefined,
        effectPeriod: undefined,
        intro: undefined,
        state: undefined,
        gmtTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加推广渠道期号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPhase(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改推广渠道期号";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePhase(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addPhase(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除推广渠道期号编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPhase(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
  }
};
</script>
